const wx_conf = require('../conf').wx
const axios = require('axios')

/*
    用户授权流程
    1. 根据授权页面 拿到 code
    2. 根据 code 拿到 access_token
    3. 根据 access_token 和 appid 拿到用户头像和昵称
*/

// 根据 code 拿到 access_token
const getUserAccessToken = async (code) => {
    console.log('根据 code 拿到 access_token 入参: ', code)
    let url = `https://api.weixin.qq.com/sns/oauth2/access_token?`
    url += `appid=${wx_conf.appid}&`
    url += `code=${code}&`
    url += `secret=${wx_conf.secret}&`
    url += `grant_type=authorization_code`
    let res = {}
    try {
        res = await axios.get(url)
        res = res.data
    } catch (error) {
        throw new Error(error)
    }
    console.log('根据 code 拿到 access_token 出参: ', res)
    return res
}

// 拿到用户信息
const getUserInfo = async (access_token) => {
    console.log('拿到用户信息 入参: ', access_token)
    let url = `https://api.weixin.qq.com/sns/userinfo?`
    url += `access_token=${access_token}&`
    url += `openid=${wx_conf.appid}&`
    url += `lang=zh_CN`
    
    let res = {}
    try {
        res = await axios.get(url)
        res = res.data
    } catch (error) {
        throw new Error(error)
    }
    console.log('拿到用户信息: ', res)
    return res
}

// ;(async () => {
//     let res = await getUserAccessToken('021SYfGa1cqUfA0CmHHa1tFZrz3SYfGQ')

//     await getUserInfo(
//         res.access_token,
//         res.openid
//     )
// })()
module.exports = {
    getUserAccessToken,
    getUserInfo
}
